package com.cyf.service.impl;

import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.cyf.activemq.network.bean.*;
import com.cyf.activemq.service.SendMsgService;
import com.cyf.db.bean.*;
import com.cyf.db.mapper.*;
import com.cyf.pay.alipay.service.AlipayService;
import com.cyf.pay.wxpay.bean.WxpayQueryOrderReq;
import com.cyf.pay.wxpay.bean.WxpayQueryOrderRsp;
import com.cyf.pay.wxpay.service.WxpayService;
import com.cyf.redis.RedisService;
import com.cyf.service.PayOrderService;
import com.cyf.util.BasicProperties;
import com.cyf.util.DateUtil;
import com.cyf.util.ObjectMapperUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by cage on 2016/12/5.
 */
@Service
public class PayOrderServiceImpl implements PayOrderService {

    private static final Logger logger = LoggerFactory.getLogger(PayOrderServiceImpl.class);
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private WxpayService wxpayService;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private FeeDetailMapper feeDetailMapper;
    @Autowired
    private InParkingMapper inParkingMapper;
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BasicProperties basicProperties;

    @Override
    public List<PayOrder> getPayOrder() throws Exception {
        List<PayOrder> payOrders;
        try {
            payOrders = payOrderMapper.getUnDownPayOrders();
        } catch (Exception e) {
            throw e;
        }
        return payOrders;
    }

  /*  @Override
    public void updatePayOrder(MqPayOrderRsp rsp) {
        try {
            if (rsp.getResult() != 0) {
                logger.info("车场保存微信账单失败！{}", rsp.getStrError());
                return;
            }
            payOrderMapper.updateSendById(rsp.getId());
            logger.debug("更新微信账单的发送状态完成！");
        } catch (Exception e) {
            logger.error("更新微信账单payOrder的发送状态send异常：{}", e);
        }
    }*/

    @Override
    public List<PayOrder> getUntreatedPayOrder() {
        List<PayOrder> payOrders;
        try {
            payOrders = payOrderMapper.getUntreatedPayOrder();
        } catch (Exception e) {
            throw e;
        }
        return payOrders;
    }

    @Override
    public void updatePayOrderStatus(PayOrder payOrder) {
        switch (payOrder.getPayWay()) {
            case PayOrder.PAY_WAY_WECHAT:
                updateWxpayOrderStatus(payOrder);
                break;
            case PayOrder.PAY_WAY_ALIPAY:
                updateAlipayOrderStatus(payOrder);
                break;
            case PayOrder.PAY_WAY_BALANCE:
                break;
            default:
                break;
        }
    }

   /* @Override
    public PayOrder updatePayOrderStatus(String transactionId, int payWay) {
        PayOrder payOrder = new PayOrder();
        switch (payWay) {
            case PayOrder.PAY_WAY_WECHAT:
                payOrder = updateWxpayOrderStatus(transactionId);
                break;
            case PayOrder.PAY_WAY_ALIPAY:
                payOrder = updateAlipayOrderStatus(transactionId);
                break;
            case PayOrder.PAY_WAY_BALANCE:
                break;
            default:
                break;
        }
        return payOrder;
    }*/

    @Override
    public void sendPayOrder(PayOrder payOrder) {
        // 更新inparking中的微信有关信息
        /*InParking inParking = inParkingMapper.getByPlate(payOrderMessage.getPlate());
        if (null != inParking) {
            int oldWechatFee = inParking.getWechatFee() == null ? 0 : inParking.getWechatFee();
            inParking.setWechatFee(payOrderMessage.getFee() + oldWechatFee);
            inParking.setWechatTime( payOrderMessage.getOutTime());
            inParking.setWechatPayTime(payOrderMessage.getPayTime());
            inParkingMapper.updateInParking(inParking);
            logger.info("更新inParking中的wechatFee、wechatTime、wechatPayTime成功！");
        }*/

        logger.info("向车场下发支付信息！");
        String uuid = UUID.randomUUID().toString();
        MqPayOrderReq mqPayOrderReq = new MqPayOrderReq();
        BeanUtils.copyProperties(payOrder, mqPayOrderReq);
        mqPayOrderReq.setOptid(MqBusinessOpt.PAYFEE);
        mqPayOrderReq.setUuid(uuid);
        mqPayOrderReq.setCreatedTime(DateUtil.convertDate2Seconds(payOrder.getCreatedTime()));
        mqPayOrderReq.setOutTime(DateUtil.convertDate2Seconds(payOrder.getOutTime()));
        mqPayOrderReq.setPayTime(DateUtil.convertDate2Seconds(payOrder.getPayTime()));
        mqPayOrderReq.setPayOrderId(payOrder.getId());
        try {
            sendMsgService.sendQueueMessageText(ObjectMapperUtils.getObjectMapper().writeValueAsString(mqPayOrderReq));
        } catch (JsonProcessingException e) {
            logger.error("转换对象至json异常：{}", e);
        }
    }

    @Override
    public PayOrder selectByOrderNo(String orderNo) {
        return payOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public void updatePayOrderCouponId(Integer couponId, String orderNo, int couponFeeTotal, int fee,String ids) {
        payOrderMapper.updatePayOrderCouponId(couponId, orderNo, couponFeeTotal, fee,ids);
    }

    @Override
    public void updatePayOrderPayStatus(Integer couponId, String orderNo, int couponFee, Date payTime,String ids) {
        payOrderMapper.updatePayOrderPayStatus(couponId, orderNo, couponFee, payTime,ids);
    }


    @Override
    public void updatePayFailOrderStatus(int id, int tradeType, int payWay, int isIsv, int apiUserId) {
        PayOrder payOrder = new PayOrder();
        payOrder.setId(id);
        payOrder.setTradeType(tradeType);
        payOrder.setPayWay(payWay);
        payOrder.setIsv(isIsv);
        payOrder.setPayStatus(PayOrder.PAYSTATUS_FAIL);
        payOrder.setApiUserId(apiUserId);
        payOrderMapper.updatePayFailOrderStatus(payOrder);
    }

    /*
    @Override
    public void sendRechargeMessage(PayOrder payOrder) {

        logger.info("向车场下发支付信息！");
        String uuid = UUID.randomUUID().toString();
        MqCarRechargeReq mqCarRechargeReq = new MqCarRechargeReq();
        mqCarRechargeReq.setOptid(MqBusinessOpt.CARRECHARGE);
        mqCarRechargeReq.setUuid(uuid);
        mqCarRechargeReq.setParkingId(payOrder.getParkingId());
        mqCarRechargeReq.setPlate(payOrder.getPlate());
        mqCarRechargeReq.setMonth(payOrder.getMonth());
        mqCarRechargeReq.setFee(payOrder.getFee());
        mqCarRechargeReq.setFeeDetailId(feeDetail.getId());
        try {
            sendMsgService.sendQueueMessageText(ObjectMapperUtils.getObjectMapper().writeValueAsString(mqCarRechargeReq));
        } catch (JsonProcessingException e) {
            logger.error("bean转json异常：{}", e);
        }
        Object result = redisService.getWithExpireTime(uuid, basicProperties.getAppNetworkTimeOut());
        if (result == null) {
            logger.info("消息队列中获取消息失败！");
            return;
        }
        MqCarRechargeRsp mqCarRechargeRsp = (MqCarRechargeRsp) result;
        if (mqCarRechargeRsp.getResult() == MqBusinessRsp.SUCCESS) {
            logger.info("网络月卡充值消息发送车场成功！");
            int payOrderId = payOrderMessage.getPayOrderId();
            payOrderMapper.updateSendById(payOrderId);
        }else{
            logger.info("网络月卡充值消息发送车场失败：{}", mqCarRechargeRsp.getStrError());
        }
    }*/

    /**
     * 更新微信支付订单的订单支付状态
     *
     * @param payOrder
     */
    private void updateWxpayOrderStatus(PayOrder payOrder) {
        WxpayQueryOrderReq wxpayQueryOrderReq = new WxpayQueryOrderReq();
        if (StringUtils.isEmpty(payOrder.getTransactionId()) || "0".equals(payOrder.getTransactionId())) {
            wxpayQueryOrderReq.setOut_trade_no(payOrder.getOrderNo());
        } else {
            wxpayQueryOrderReq.setTransaction_id(payOrder.getTransactionId());
        }
        WxpayQueryOrderRsp wxpayQueryOrderRsp = wxpayService.queryOrder(wxpayQueryOrderReq);
        logger.info("微信支付查询结果：{}", wxpayQueryOrderRsp);
        if (WxpayQueryOrderRsp.SUCCESS.equals(wxpayQueryOrderRsp.getReturn_code()) && WxpayQueryOrderRsp.SUCCESS.equals(wxpayQueryOrderRsp.getResult_code())) {
            if (WxpayQueryOrderRsp.TRADE_STATE_SUCCESS.equals(wxpayQueryOrderRsp.getTrade_state())) {
                // 更新支付账单
                payOrder.setPayStatus(PayOrder.PAY_SUCCESS);
                payOrder.setTransactionId(wxpayQueryOrderRsp.getTransaction_id());
                payOrder.setOpenid(wxpayQueryOrderRsp.getOpenid());
                try {
                    payOrder.setPayTime(WxpayQueryOrderRsp.TIME_END_FORMAT.parse(wxpayQueryOrderRsp.getTime_end()));
                } catch (ParseException e) {
                    logger.error("更新微信支付账单时，时间格式化异常：{}", e);
                }
                payOrder.setActualFee(wxpayQueryOrderRsp.getCash_fee());
                payOrderMapper.updatePayOrder(payOrder);
            } else if (WxpayQueryOrderRsp.TRADE_STATE_PAYERROR.equals(wxpayQueryOrderRsp.getTrade_state()) || WxpayQueryOrderRsp.TRADE_STATE_CLOSED.equals(wxpayQueryOrderRsp.getTrade_state())) {
                // 更新支付账单
                payOrder.setPayStatus(PayOrder.PAY_FAIL);
                payOrder.setTransactionId(wxpayQueryOrderRsp.getTransaction_id());
                payOrder.setOpenid(wxpayQueryOrderRsp.getOpenid());
                payOrderMapper.updatePayOrder(payOrder);
            } else {
                // 不更新支付账单
            }
        } else {
            logger.debug("不更新支付账单！");
        }
    }

   /* private PayOrder updateWxpayOrderStatus(String transactionId) {
        PayOrder payOrder = null;
        WxpayQueryOrderReq wxpayQueryOrderReq = new WxpayQueryOrderReq();
        wxpayQueryOrderReq.setTransaction_id(transactionId);
        WxpayQueryOrderRsp wxpayQueryOrderRsp = wxpayService.queryOrder(wxpayQueryOrderReq);
        if (wxpayQueryOrderRsp == null) {
            return null;
        }
        String orderNo = wxpayQueryOrderRsp.getOut_trade_no();
        if (!StringUtils.isEmpty(orderNo)) {
            payOrder = payOrderMapper.getByOrderNo(orderNo);
        }
        if (WxpayQueryOrderRsp.SUCCESS.equals(wxpayQueryOrderRsp.getReturn_code()) && WxpayQueryOrderRsp.SUCCESS.equals(wxpayQueryOrderRsp.getResult_code())) {
            if (WxpayQueryOrderRsp.TRADE_STATE_SUCCESS.equals(wxpayQueryOrderRsp.getTrade_state())) {
                if (payOrder != null) {
                    // 更新支付账单
                    payOrder.setPayStatus(PayOrder.PAY_SUCCESS);
                    payOrder.setTransactionId(wxpayQueryOrderRsp.getTransaction_id());
                    payOrder.setOpenid(wxpayQueryOrderRsp.getOpenid());
                    try {
                        payOrder.setPayTime(WxpayQueryOrderRsp.TIME_END_FORMAT.parse(wxpayQueryOrderRsp.getTime_end()));
                    } catch (ParseException e) {
                        logger.error("更新微信支付账单时，时间格式化异常：{}", e);
                    }
                    payOrderMapper.updatePayOrder(payOrder);
                }

            } else if (WxpayQueryOrderRsp.TRADE_STATE_PAYERROR.equals(wxpayQueryOrderRsp.getTrade_state())) {
                if (payOrder != null) {
                    // 更新支付账单
                    payOrder.setPayStatus(PayOrder.PAY_FAIL);
                    payOrder.setTransactionId(wxpayQueryOrderRsp.getTransaction_id());
                    payOrder.setOpenid(wxpayQueryOrderRsp.getOpenid());
                    payOrderMapper.updatePayOrder(payOrder);
                }
            } else {
                // 不更新支付账单
            }
        } else {
            logger.debug("不更新支付账单！");
        }
        return null;
    }*/

    /**
     * 更新微信支付订单的订单支付状态
     *
     * @param payOrder
     */
    private void updateAlipayOrderStatus(PayOrder payOrder) {
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        if (StringUtils.isEmpty(payOrder.getTransactionId()) || "0".equals(payOrder.getTransactionId())) {
            model.setOutTradeNo(payOrder.getOrderNo());
        } else {
            model.setTradeNo(payOrder.getTransactionId());
        }
        AlipayTradeQueryResponse alipayTradeQueryResponse = alipayService.queryOrder(model);
        if ("ACQ.TRADE_NOT_EXIST".equals(alipayTradeQueryResponse.getSubCode()) && (new Date().getTime() - payOrder.getCreatedTime().getTime() < 30 * 60 * 1000)) {
            return;
        }
        if (alipayTradeQueryResponse.isSuccess()) {
//            WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
            if ("WAIT_BUYER_PAY".equals(alipayTradeQueryResponse.getTradeStatus())) {
                logger.info("等待买家支付！");
                return;
            }
            if ("TRADE_SUCCESS".equals(alipayTradeQueryResponse.getTradeStatus()) || "TRADE_FINISHED".equals(alipayTradeQueryResponse.getTradeStatus())) {
                // 更新支付账单
                payOrder.setPayStatus(PayOrder.PAY_SUCCESS);
                payOrder.setTransactionId(alipayTradeQueryResponse.getTradeNo());
                payOrder.setPayTime(alipayTradeQueryResponse.getSendPayDate());
                payOrder.setActualFee((int) (Double.parseDouble(alipayTradeQueryResponse.getReceiptAmount()) * 100));
                payOrderMapper.updatePayOrder(payOrder);
                return;
            }
        }
        // 更新支付账单
        payOrder.setPayStatus(PayOrder.PAY_FAIL);
        payOrderMapper.updatePayOrder(payOrder);
    }

    /**
     * 更新支付宝支付订单的订单支付状态
     *
     * @param transactionId 交易订单号
     * @return PayOrder  订单号错误,返回null
     */
    /*private PayOrder updateAlipayOrderStatus(String transactionId) {
        PayOrder payOrder = null;
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setTradeNo(transactionId);
        AlipayTradeQueryResponse alipayTradeQueryResponse = alipayService.queryOrder(model);
        if (alipayTradeQueryResponse == null) {
            return null;
        }
        String orderNo = alipayTradeQueryResponse.getOutTradeNo();
        if (!StringUtils.isEmpty(orderNo)) {
            payOrder = payOrderMapper.getByOrderNo(orderNo);
        }



        // TODO: 2017/5/6  
        if (alipayTradeQueryResponse.isSuccess()) {
            if (payOrder != null) {
                // 更新支付账单
                payOrder.setPayStatus(PayOrder.PAY_SUCCESS);
                payOrder.setTransactionId(alipayTradeQueryResponse.getTradeNo());
                payOrder.setPayTime(alipayTradeQueryResponse.getSendPayDate());
                payOrderMapper.updatePayOrder(payOrder);
            }
        } else {
            if (payOrder != null) {
                // 更新支付账单
                payOrder.setPayStatus(PayOrder.PAY_FAIL);
                if (alipayTradeQueryResponse.getTradeNo() != null) {
                    payOrder.setTransactionId(alipayTradeQueryResponse.getTradeNo());
                }
                if (alipayTradeQueryResponse.getSendPayDate() != null) {
                    payOrder.setPayTime(alipayTradeQueryResponse.getSendPayDate());
                }
                payOrderMapper.updatePayOrder(payOrder);
            }
        }
        return payOrder;
    }*/
}
